﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace ExpLib.Web.SSO
{
    public class SSOAuthenticateHttpModule : IHttpModule
    {

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
            context.BeginRequest += new EventHandler(context_BeginRequest);


        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;

            HttpContext context = application.Context;
            HttpResponse Response = context.Response;
            Response.AddHeader("PP", "CP=CAO PSA OUR");//加上这个,防止在Iframe的时间Cookie丢失
        }



        void context_AuthenticateRequest(object sender, EventArgs e)
        {

            HttpApplication application = (HttpApplication)sender;

            HttpContext context = application.Context;

            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;

            if (Request.IsAuthenticated)
            {
                return;
            }
            else
            {
                String signData = Request.QueryString["s"];
                String data = Request.QueryString["d"];
                String salt = Request.Cookies["salt"] == null ? String.Empty: Request.Cookies["salt"].Value;

                if (String.IsNullOrEmpty(data) || String.IsNullOrEmpty(salt)
                    || String.IsNullOrEmpty(signData))
                {
                    DoAuth(context);
                }
                else
                {
                    using (SignHelper helper = new SignHelper())
                    {
                        helper.FromXmlString(GetPublicKey());

                        if (helper.ValidataData(data + salt, signData))
                        {
                            SetTicket(context, data);
                        }
                        else
                        {
                            DoAuth(context);
                        }
                    }
                }

               
            }

        }

        private void DoAuth(HttpContext context)
        {
            String salt = new Random().Next().ToString();

            context.Response.Cookies["salt"].Value = salt;

            String ssoUrl = GetSSOUrl() + "?ReturnUrl=" + context.Request.Url.ToString() + "&salt=" + salt;

            context.Response.Redirect(ssoUrl);
        }

        protected virtual void SetTicket(HttpContext context,String data)
        { 

        
        }

        protected virtual String GetPublicKey()
        {
            return "<RSAKeyValue><Modulus>n01P4RTisCpUKg+XQWEuOFSBKNWPxsxEZHVVbXl07p6lfdqBAfmgVtetMtKSCFwhLD8sROosoWDqf7ZrniBg1LAYyFpdik4XEAKXuy+qnfB9EnQCvM3LluJlk/Cz1JgEBTy5XKLszfeG5+Xo4QD9VxikOxiapZSo5qg9HML8OXE=</Modulus><Exponent>AQAB</Exponent><P>y4doVLfUOX+J5EUlmN4R+2IvYIjHaVn3rLYCrEgbQ3GAm9fHRc/BtVl6Oon77R3TSuwcybfUlNRG+QKxyctHaw==</P><Q>yF7+5Tf/Oatu4f8CdxmHLY9obb9F/fN+kNPY7HBRmTwopv3f3VyOdSQewpB5af8a1vIIGFM8NMF6H2hbRn9lkw==</Q><DP>U/MOPaN1jiHlJpq+30b5886T7CV+2x2Y40xP3fAADtmKSr2+HDWNmNfHas3vc+aReJ3bYfjJXnoQrDVIUAvg8Q==</DP><DQ>YYMJnVfRF6m8frNx6bA8vwlpku9hCqOzVpwil35Z168VQZ+PkNT4Zz260oko7VK/JxgGpH/tbucxnZNVyEs7jQ==</DQ><InverseQ>f3F2gytVjOLm9EKkFFPktR8kSQ6g+0KQ07h23hrEKUk03puNsXAVR7knmKxv7rrl26Ry4MYlLPiJCVbJX4Bx1g==</InverseQ><D>cDYxUkc39weaCZa54N/ngt5jrLPidxJkCq9r4ZVwfLVbtW84+H8yJnn+EpKpMyJSa6yELncVwQdXp2aEH/qGua5e/nOtVOSY8TUZWcU2gONeqKIdAnib17rI2u1+te8MQfWgJLU8jmDjcaYj4UrkPIu3tOXx9cmmTwsj2NLyphE=</D></RSAKeyValue>";
        }
        protected virtual String GetSSOUrl()
        {
            return FormsAuthentication.LoginUrl ;
        }
    }
}
